import os
from django.conf import settings
from django.http import Http404
from django.shortcuts import render
from django.template import Template
from django.utils._os import safe_join
#from robot import key_input
import re
import random

regular_search_mobile_device = 'Android|iPhone'
reqularSearchMobileDevicePattern = re.compile(regular_search_mobile_device, re.MULTILINE)
def get_page_or_404(name):
	"""Return page content as a Django template or raise 404 error."""
	try:
		file_path = safe_join(settings.SITE_PAGES_DIRECTORY, name)
		print (file_path)
	except ValueError:
		raise Http404('Page Not Found')
	else:
		if not os.path.exists(file_path):
			raise Http404('Page Not Found')
	with open(file_path, 'r') as f:
		page = Template(f.read())
	return page

def index(request):
	return render(request, 'index.html')

def robot(request):
	#if 'ctrl' in request.GET and request.GET['ctrl']:
		#key_input(request.GET['ctrl'])
	mobileDevice = False
	agent = request.META.get('HTTP_USER_AGENT', None)
	searchMobileDeviceResult = reqularSearchMobileDevicePattern.search(agent)
	if (searchMobileDeviceResult is None):
		mobileDevice = False
	else:
		mobileDevice = True
	context = {
		'mobileDevice':mobileDevice,
		}
	return render(request, 'robot.html', context)
